package sweet.helper
import java.io._
import java.util.jar.Manifest
/** Provide helper methods to read a manifest file content from jar or exploded classpath. */
object ManifestHelper {
  /** read manifest Attribute of manifest as map from a inputStream. */
  def manifestAttributes(inputStream: InputStream): scala.collection.Map[String, String] = {    
    val mf = new Manifest()
    mf.read(inputStream)
    val attr = mf.getMainAttributes()
    val res = new scala.collection.mutable.HashMap[String, String]
    for((k,v) <- new SMap[Object, Object](attr)){
      res(k.toString) = v.toString  
    }
    res.readOnly
  }
  
  /** read manifest Attribute of manifest as map from a classpath. */
  def manifestAttributes(classPath: String): scala.collection.Map[String, String] = {  
    val manifest = new File(classPath+"/META-INF/MANIFEST.MF")
    if(manifest.exists){
      manifestAttributes(new FileInputStream(manifest))
    }else{
      Map.empty[String, String]
    }
  }
  /** read manifest Attribute of manifest as map from the jar that this class is loaded with.*/
  def manifestAttributes(classLoader: ClassLoader): scala.collection.Map[String, String] = {
    val manifestInputStream = classLoader.getResourceAsStream("META-INF/MANIFEST.MF")
    if(manifestInputStream != null){
      manifestAttributes(manifestInputStream)
    }else{
      Map.empty[String, String]
    }
  }
}
